package cn.com.callback

import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import cn.com.kh.LogToDB
import cn.com.elite.EliteBean
import cn.com.kh.result.FddResult
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * @projectName: Groovy*
 * @package: com.elite.groovy.callback*
 * @className: apiFDDAPIProxy
 * @description: 法大大代理接口
 * @author: Tao
 * @date: 2024-05-19 15:00
 * @version: 1.0
 */
public class apiFDDAPIProxy implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiFDDAPIProxy.class);
    private static String URL;
    private static String APPKEY;
    private static String APPID;

    String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        long startTime = System.currentTimeMillis();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        JSONObject resBodyJson = JSONObject.fromObject(new FddResult(FddResult.SUCCESS, "操作成功", null));

        // 调用IP过滤
        if (KHDBConfig.getParam(eliteBean, "#APIIP") == "1" && !KHUtil.getRemoteHost(request)) {
            resBodyJson = JSONObject.fromObject(new FddResult(FddResult.WARN, "API被非法IP调用-Request Not Allow!" + KHUtil.getRemoteHost(request), null));
            log.warn(resBodyJson);
            return resBodyJson;
        }

        String callMethod = request.getMethod();
        log.debug("HTTP请求调用类型 getMethod:" + callMethod);
        if (callMethod != "POST" && callMethod != "GET") {
            resBodyJson = JSONObject.fromObject(new FddResult(FddResult.ERROR, "HTTP请求调用类型错误，接口调用失败：" + callMethod, null));
            log.error(resBodyJson);
            return resBodyJson;
        }

        // 获取所有Header
        Map<String, String> headerMap = new HashMap<String, String>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            log.debug("*Call Header-" + key + ":" + value);

            headerMap.put(key, value);
        }

        // 获取所有参数名
        Map<String, String> paramsMap = new HashMap<String, String>();
        Enumeration ep = request.getParameterNames();
        while (ep.hasMoreElements()) {
            String key = (String) ep.nextElement();
            String value = request.getParameter(key);
            log.debug("#Call Parameter-" + key + ":" + value);
            paramsMap.put(key, value);

        }

        // 获取数据源List<Map<String, Object>>
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        // 获取调用数据
        String callBodyStr = "";
        if (callMethod.equals("GET")) {
            callBodyStr = request.getQueryString();
            log.info("接收调用GET参数信息：" + callBodyStr);
        } else if (callMethod.equals("POST")) {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                callBodyStr += line;
            }
            log.info("接收调用POST报文信息：" + System.getProperty("line.separator") + callBodyStr);
        }

        try {
            // 获取代理地址参数
            String proxyURL = request.getParameter("callURL");
            log.debug("获取代理地址参数：" + proxyURL);
            if (KHUtil.isNull(proxyURL)) {
                resBodyJson = JSONObject.fromObject(new FddResult(FddResult.ERROR, "获取代理地址参数callURL错误", null));

            } else {
                HashMap<String, Object> headMap = new HashMap<>();
                headMap.put("Content-Type", "application/json");

                String resBodyStr = Util.doHttpPostUseHead(proxyURL, callBodyStr, "UTF-8", 120000, 0, headMap);
                log.debug("代理请求返回报文：" + resBodyStr);

                // 解析请求报文
                resBodyJson = JSONObject.fromObject(resBodyStr);

            }

        } catch (Exception e) {
            resBodyJson = JSONObject.fromObject(new FddResult(FddResult.ERROR, "HTTP请求调用错误，接口处理异常：" + e.getMessage(), null));
            log.error(resBodyJson, e);

        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "法大大代理接口", "apiFDDAPIProxy", callBodyStr, resBodyJson.toString(), (System.currentTimeMillis() - startTime).toString(), callMethod + ":" + paramsMap.toString());
        }
        return resBodyJson;
    }
}